package leetcode_201_300;

public class LeeCode_227 {
    public static void main(String[] args) {
//        System.out.println(calculate("3+2*2"));
        System.out.println(calculate("3/  2 "));
//        System.out.println(calculate("3+5/2"));
    }
    private static int calculate(String s) {
        char[] cs = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char c : cs) {
            if (c != ' '){
                sb.append(c);
            }
        }
        s = sb.toString();
        int ans = 0;
        String[] split = s.split("\\+");
        for (String s0 : split) {
            int ans1 = 0;
            String[] split1 = s0.split("-");
            for (int i = 0; i < split1.length; i++) {
                String s1 = split1[i];
                int n = s1.length();
                int ans2 = 0;
                int flag = -1;
                int index = 0;
                int now = 0;
                while (true) {
                    int sum = 0;
                    while (index < n && s1.charAt(index) >= '0' && s1.charAt(index) <= '9') {
                        sum = sum * 10 + s1.charAt(index) - '0';
                        index++;
                    }
                    if (flag == -1){
                        now += sum;
                    }else if (flag == 0){
                        now *= sum;
                    }else {
                        now /= sum;
                    }
                    if (index >= n){
                        ans2 = now;
                        break;
                    }
                    if (s1.charAt(index) == '*'){
                        flag = 0;
                        index++;
                    }else {
                        flag = 1;
                        index++;
                    }
                }
                if (i == 0){
                    ans1 += ans2;
                }else {
                    ans1 -= ans2;
                }
            }
            ans += ans1;
        }
        return ans;
    }
}
